import requests

from urllib import parse
import os
from urllib import request
# 单线程下载王者荣耀壁纸

def send_request():
    url = 'https://apps.game.qq.com/cgi-bin/ams/module/ishow/V1.0/query/workList_inc.cgi?activityId=2735&sVerifyCode=ABCD&sDataType=JSON&iListNum=20&totalpage=0&page=1&iOrder=0&iSortNumClose=1&iAMSActivityId=51991&_everyRead=true&iTypeId=2&iFlowId=267733&iActId=2735&iModuleId=2735&_=1747572781165'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
        'referer': 'https://pvp.qq.com/',
    }
    resp = requests.get(url, headers=headers)
    return resp.json()


def exact_url(data):
    image_url_list = []
    for i in range(1, 9):
        image_url = parse.unquote(data['sProdImgNo_{}'.format(i)]).replace('200', '0')
        image_url_list.append(image_url)
    return image_url_list


def parse_json(json_data):
    d = {}
    data_list = json_data['List']
    for data in data_list:
        image_url_list = exact_url(data)
        sProdName = parse.unquote(data['sProdName'])
        d[sProdName] = image_url_list
        # for item in d:
        #     print(item, d[item])
        save_jpg(d)


def save_jpg(d):
    for key in d:
        dirpath = os.path.join('image', key.strip(' '))
        # os.mkdir(dirpath)
        os.makedirs(dirpath, exist_ok=True)
        for index, image_url in enumerate(d[key]):
            try:
                request.urlretrieve(image_url, os.path.join(dirpath, '{}.jpg'.format(index + 1)))
                print('{}下载完毕'.format(d[key][index]))
            except:
                print('{}下载出错'.format(d[key][index]))


def start():
    json_data = send_request()
    parse_json(json_data)


if __name__ == '__main__':
    start()
